package com.aircms.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @author air
 * @create 2018-09-23 下午4:27
 */
public class FileUtils {
    private String relativePath = "";       // 相对路径
    private String absolutePath = "";       // 绝对路径
    private String oldName = "";
    private String newName = "";


    /**
     * @param file 文件
     * @param path 文件存放路径
     * @return
     */
    public boolean upload(MultipartFile file, String path) {
        LocalDate toDay = LocalDate.now();

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重新命名文件
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        String relativePath = toDay + "/" + newFileName + suffixName;      // 相对路径
        String realPath = path + relativePath;

        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            setOldName(fileName);
            setNewName(newFileName + suffixName);
            setRelativePath(relativePath);
            setAbsolutePath(realPath);
            return true;
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return false;
    }

    public String getRelativePath() {
        return relativePath;
    }

    private void setRelativePath(String relativePath) {
        this.relativePath = relativePath;
    }

    public String getAbsolutePath() {
        return absolutePath;
    }

    private void setAbsolutePath(String absolutePath) {
        this.absolutePath = absolutePath;
    }

    public String getOldName() {
        return oldName;
    }

    private void setOldName(String oldName) {
        this.oldName = oldName;
    }

    public String getNewName() {
        return newName;
    }

    private void setNewName(String newName) {
        this.newName = newName;
    }
}
